package com.translator.engine.api;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Random;

/**
 * 百度翻译引擎实现
 * 使用百度翻译API进行文本翻译
 */
public class BaiduTranslationEngine extends AbstractAPITranslationEngine {
    
    private static final String API_URL = "http://api.fanyi.baidu.com/api/trans/vip/translate";
    private String appId; // 百度翻译API需要appId和密钥
    
    /**
     * 构造函数
     */
    public BaiduTranslationEngine() {
        super("百度翻译");
        // 从apiKey中提取appId和密钥（格式：appId:密钥）
        if (apiKey != null && apiKey.contains(":")) {
            String[] parts = apiKey.split(":", 2);
            this.appId = parts[0];
            this.apiKey = parts[1];
        }
    }
    
    @Override
    protected String doTranslate(String sourceText, String sourceLanguageCode, String targetLanguageCode) throws Exception {
        // 转换语言代码为百度API格式
        String from = convertLanguageCode(sourceLanguageCode);
        String to = convertLanguageCode(targetLanguageCode);
        
        // 生成随机数和签名
        String salt = String.valueOf(new Random().nextInt(10000));
        String sign = generateSign(appId, sourceText, salt, apiKey);
        
        // 构建请求URL
        StringBuilder urlBuilder = new StringBuilder(API_URL);
        urlBuilder.append("?q=").append(URLEncoder.encode(sourceText, "UTF-8"));
        urlBuilder.append("&from=").append(from);
        urlBuilder.append("&to=").append(to);
        urlBuilder.append("&appid=").append(appId);
        urlBuilder.append("&salt=").append(salt);
        urlBuilder.append("&sign=").append(sign);
        
        // 发送请求
        URL url = new URL(urlBuilder.toString());
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        
        // 读取响应
        StringBuilder response = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
        }
        
        // 解析响应
        String responseBody = response.toString();
        String translatedText = parseResponse(responseBody);
        
        return translatedText;
    }
    
    /**
     * 生成百度翻译API签名
     * 
     * @param appId 应用ID
     * @param query 查询文本
     * @param salt 随机数
     * @param secretKey 密钥
     * @return 签名
     */
    private String generateSign(String appId, String query, String salt, String secretKey) throws Exception {
        String str = appId + query + salt + secretKey;
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] bytes = md.digest(str.getBytes("UTF-8"));
        StringBuilder sign = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(b & 0xFF);
            if (hex.length() == 1) {
                sign.append("0");
            }
            sign.append(hex);
        }
        return sign.toString();
    }
    
    /**
     * 解析API响应，提取翻译结果
     * 
     * @param responseBody API响应体
     * @return 翻译后的文本
     */
    private String parseResponse(String responseBody) {
        // 简单解析，实际应用中应使用JSON库
        int resultStart = responseBody.indexOf("\"dst\":\"") + 7;
        int resultEnd = responseBody.indexOf("\"", resultStart);
        
        if (resultStart >= 7 && resultEnd > resultStart) {
            return responseBody.substring(resultStart, resultEnd);
        }
        
        return "翻译失败，无法解析响应";
    }
    
    /**
     * 转换语言代码为百度API格式
     * 
     * @param languageCode 标准语言代码
     * @return 百度API语言代码
     */
    private String convertLanguageCode(String languageCode) {
        // 大多数语言代码可以直接使用，特殊情况需要转换
        switch (languageCode) {
            case "zh": return "zh";
            case "en": return "en";
            case "ja": return "jp";
            case "ko": return "kor";
            case "fr": return "fra";
            case "de": return "de";
            case "es": return "spa";
            case "it": return "it";
            case "ru": return "ru";
            case "pt": return "pt";
            case "ar": return "ara";
            case "hi": return "hi";
            case "th": return "th";
            case "vi": return "vie";
            default: return languageCode;
        }
    }
    
    @Override
    public boolean isConfigValid() {
        return apiKey != null && !apiKey.isEmpty() && appId != null && !appId.isEmpty();
    }
}